class Shop::OrderItemsController < ShopController
  def index
    @order_items = OrderItem.joins(:order).where("orders.shop_id = ?", current_shoper.shop.id)
    if params[:between].presence
      if params[:between] == 'today'
        @order_items = @order_items.today
      elsif params[:between] == 'by_week'
        @order_items = @order_items.by_week
      elsif params[:between] == 'by_month'
        @order_items = @order_items.by_month
      end
    end
    if params[:state].presence
      @order_items = @order_items.where(state: params[:state])
    end
    @order_items = @order_items.order("created_at DESC").page(params[:page]).per(params[:per])
  end

  def edit
    @order_item = OrderItem.find params[:id]
    if not @order_item.after_sale?
      redirect_to shop_order_items_path(state: :after_sale), notice: "该退款项目不能审核." and return
    end
  end

  def update
    @order_item = OrderItem.find params[:id]
    if @order_item.after_sale?
      if @order_item.update order_item_params
        redirect_to shop_order_items_path(state: :after_sale), notice: "审核成功." and return
      else
        redirect_to shop_order_items_path(state: :after_sale), notice: "审核出错." and return
      end
    else
      redirect_to shop_order_items_path(state: :after_sale), notice: "该退款项目不能审核." and return
    end
  end

  def refund
    @order_item = OrderItem.find params[:id]
    if @order_item.agree?
      redirect_to shop_order_items_path(state: :after_sale), notice: "退款成功." and return
    else
      redirect_to shop_order_items_path(state: :after_sale), notice: "该项目不是同意状态，不能退款." and return
    end
  end

  private

  def order_item_params
    params.require(:order_item).permit(:state)
  end
  
end
